package com.xiaoyu.base.remoteconfig;

import android.text.TextUtils;

import com.xiaoyu.base.remoteconfig.base.ConfigLinkedDataUpdater;
import com.xiaoyu.base.remoteconfig.base.ConfigValueGetter;
import com.xiaoyu.base.remoteconfig.base.ConfigValueUpdater;

import in.srain.cube.request.JsonData;

public class ConfigValues implements ConfigValueGetter, ConfigValueUpdater {

    private volatile String mHash;
    private volatile JsonData mDict;
    private ConfigLinkedDataUpdater mConfigLinkedDataUpdater;

    ConfigValues() {
        this.mHash = "";
        this.mDict = JsonData.newMap();
    }

    @Override
    public void update(JsonData jsonData, Runnable callback) {
        String hash = jsonData.optString("hash");
        if (TextUtils.isEmpty(hash)) {
            return;
        }
        synchronized (this) {
            mHash = hash;
            mDict = jsonData.optJson("configs");
        }
        if (mConfigLinkedDataUpdater != null) {
            mConfigLinkedDataUpdater.update();
        }
        callback.run();
    }

    boolean isShouldRefreshHash(String other) {
        return !TextUtils.isEmpty(other) && !TextUtils.equals(mHash, other);
    }

    @Override
    public int getInt(String key, int def) {
        return mDict.optInt(key, def);
    }

    @Override
    public boolean getBoolean(String key, boolean def) {
        return mDict.optBoolean(key, def);
    }

    @Override
    public String getString(String key, String def) {
        return mDict.optString(key, def);
    }

    @Override
    public long getLong(String key, int def) {
        return mDict.optLong(key, def);
    }

    @Override
    public double getDouble(String key, double def) {
        return mDict.optDouble(key, def);
    }

    public void setConfigLinkedDataUpdater(ConfigLinkedDataUpdater configLinkedDataUpdater) {
        mConfigLinkedDataUpdater = configLinkedDataUpdater;
    }
}
